<template>
  <div :style="item.width ? {width: item.width} : {}" :class="{'mobile-form-item':showMobilePage}">
    <el-date-picker
      v-if="item.type === 'date' && !item.disabled"
      v-model="value[item.keyword]"
      :unlink-panels="true"
      :clearable="true"
      :editable="false"
      :format="item.format || 'yyyy/MM'"
      :class="item.class"
      :placeholder="item.placeholder || '请选择月份'"
      :type="item.dateType || 'month'"
      value-format="timestamp"
      size="small" />
    <el-date-picker
      v-if="item.type === 'rangeDate' && !item.disabled"
      v-model="value[item.keyword]"
      :unlink-panels="true"
      :clearable="true"
      :editable="false"
      :picker-options="setPickerOptions(item.monthSpan, item.addQuickOptions)"
      :start-placeholder="item.startPlaceholder || '开始日期'"
      :end-placeholder="item.endPlaceholder || '结束日期'"
      :format="item.format || 'yyyy/MM/dd'"
      :class="item.class"
      :type="item.timeType ? item.timeType : 'datetimerange'"
      :default-time="!item.timeType || item.timeType === 'datetimerange' ? ['00:00:00', '23:59:59'] : null"
      size="small"
      value-format="timestamp"
      @change="datePickerTime($event, item.keyword, item.monthSpan)" />
  </div>
</template>

<script>
import { mapState } from 'vuex';
export default {
  props: {
    item: {
      type: Object,
      default: () => {
        return {};
      }
    },
    value: {
      type: Object,
      default: () => {
        return {};
      }
    }
  },
  data() {
    return {
      pickDate: '',
      pickerOptions: {
        shortcuts: [{
          text: '上月',
          onClick(picker) {
            const start = new Date();
            const nowYear = start.getFullYear();
            const currentMonth = start.getMonth();
            const prevMonth = start.getMonth() - 1;
            const prevMonthDate = new Date(nowYear, prevMonth, 1);
            const currentMonthDate = new Date(nowYear, currentMonth, 0, '23', '59', '59');
            picker.$emit('pick', [prevMonthDate, currentMonthDate]);
          }
        }, {
          text: '本月',
          onClick(picker) {
            const start = new Date();
            const nowMonth = start.getMonth(); // 当前月
            const nowYear = start.getFullYear(); // 当前年
            const nextMonth = start.getMonth() + 1; // 当前月

            // 本月的开始时间
            const startDate = new Date(nowYear, nowMonth, 1);
            const endDate = new Date(nowYear, nextMonth, 0, '23', '59', '59');
            picker.$emit('pick', [startDate, endDate]);
          }
        }, {
          text: '本年',
          onClick(picker) {
            const start = new Date();
            const nowYear = start.getFullYear();
            const prevMonthDate = new Date(nowYear, 0, 1);
            const currentMonthDate = new Date(nowYear, 11, 31, '23', '59', '59');
            picker.$emit('pick', [prevMonthDate, currentMonthDate]);
          }
        }]
      }
    };
  },
  computed: {
    ...mapState({
      'showMobilePage': state => state.app.showMobilePage
    })
  },
  methods: {
    /**
     * 设置可选时间跨度
     * @param {number} monthSpan：范围月数
     * @param {array} addQuickOptions：需要添加的快捷选项的天数
     */
    expandOptions(monthSpan) {
      return {
        onPick: pick => {
          this.pickDate = pick;
        },
        disabledDate: date => {
          if (!monthSpan) return false;
          const { minDate, maxDate } = this.pickDate;
          if (minDate && !maxDate) {
            const minDataStamp = minDate.valueOf();
            // 往前最大可选日期
            const maxPreStamp = moment(minDataStamp).subtract(Number(monthSpan), 'months').valueOf();
            // 往后最大可选日期
            const maxNextStamp = moment(minDataStamp).add(Number(monthSpan), 'months').valueOf();
            if (minDataStamp > date.valueOf()) {
              const preDiffStamp = minDataStamp - maxPreStamp;
              return minDataStamp - date.valueOf() > preDiffStamp;
            } else {
              const nextDiffStamp = maxNextStamp - minDataStamp;
              return date.valueOf() - minDataStamp > nextDiffStamp;
            }
          }
        }
      };
    },
    setPickerOptions(monthSpan, addQuickOptions = []) {
      const currPickerOptions = _.cloneDeep(this.pickerOptions);
      // 最大可选范围小于12个月，移除‘本年’快捷项
      if (monthSpan < 12) {
        currPickerOptions.shortcuts = currPickerOptions.shortcuts.filter(item => item.text !== '本年');
      }
      if (addQuickOptions.length > 0) {
        const temp = [];
        addQuickOptions.forEach(item => {
          temp.push(this.addQuickOptions(item));
        });
        currPickerOptions.shortcuts = currPickerOptions.shortcuts.concat(temp);
      }
      return this.showMobilePage ? !monthSpan ? null : this.expandOptions(monthSpan) : Object.assign(currPickerOptions, this.expandOptions(monthSpan));
    },
    datePickerTime(e, keyword, monthSpan = null) {
      if (e == null) this.pickDate = '';
      let val = e;
      if (monthSpan && e) {
        const startTime = e[0];
        const endTime = e[1];
        const maxTime = moment(startTime).add(Number(monthSpan), 'months').valueOf();
        if (maxTime + 86400000 <= endTime) {
          this.pickDate = '';
          val = null;
          this.value[keyword] = null;
          this.$message.warning(`筛选范围不能超过${monthSpan}个月哦~`);
        }
      }
      this.$emit('datePickerTime', { val, key: keyword });
    },
    addQuickOptions(day) {
      // 设置day天数后的快捷选项
      if (day > 0) {
        return {
          text: `${day}天`,
          onClick(picker) {
            const start = new Date(new Date().toLocaleDateString()).getTime();
            const end = start + 1000 * 60 * 60 * 24 * day;
            picker.$emit('pick', [start, end]);
          }
        };
      }
    }
  }
};
</script>

<style lang="scss" scoped>
.el-date-editor {
  width: 240px;
}
::v-deep {
  .el-form-item__label {
    display: flex;
    justify-content: flex-end;
    align-items: center;
    height: 32px;
  }
}
.mobile-form-item {
  &::v-deep {
    .el-form-item__label {
      display: flex;
      justify-content: flex-start;
      align-items: center;
      height: 32px;
    }
  }
}
.input-form-label {
  line-height: 1.2 !important;
}
</style>
<style lang="scss">
.el-time-panel {
  width: 156px;
}
</style>
